package com.yanwq.nwa.message;

import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.text.TextUtils;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.Toast;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.yanwq.nwa.MApplication;
import com.yanwq.nwa.R;
import com.yanwq.nwa.im.ChatMgr;
import com.yanwq.nwa.im.EventCallback;
import com.yanwq.nwa.im.EventMgr;
import com.yanwq.nwa.entity.Message;
import com.yanwq.nwa.user.UserMgr;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

public class MailSendActivity extends AppCompatActivity {

    @BindView(R.id.ms_content)
    EditText msContent;
    @BindView(R.id.ms_send)
    Button msSend;
    @BindView(R.id.activity_mail_send)
    LinearLayout activityMailSend;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_mail_send);
        ButterKnife.bind(this);
        EventMgr.getInstance().registerEventCallback(new EventCallback() {
            @Override
            public void onSuccess(String data) {
                JSONObject jsonObject = JSON.parseObject(data);
                if ("broadcast".equalsIgnoreCase(jsonObject.getString("event"))) {
                    Message message = JSON.parseObject(data, Message.class);
                    MApplication.getDaoSession().getMessageDao().save(message);
                    if (message.getFrom_uuid().equals(UserMgr.getUuid())) {
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                Toast.makeText(getApplicationContext(), "发送成功", Toast.LENGTH_SHORT).show();
                            }
                        });
                    }
                }
            }

            @Override
            public void onFailure(Failure failure) {

            }
        });
    }

    @OnClick(R.id.ms_send)
    public void onViewClicked() {
        String content = msContent.getText().toString();
        if (TextUtils.isEmpty(content)) {
            Toast.makeText(this, "Content empty!!", Toast.LENGTH_SHORT).show();
            return;
        }
        ChatMgr.sendBroadcast(content);
    }
}
